import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.BlockingDeque;

public class Indexer implements Runnable {
	private final BlockingDeque<File>[] dequeues;
	private final int index;
	private int indexedCount = 0;
	private int stolenCount = 0;

	public Indexer(BlockingDeque<File>[] dequeues, int index) {
		this.dequeues = dequeues;
		this.index = index;
	}

	public void run() {
		outer: while (true) {
			File file = dequeues[index].pollFirst();
			if (file != null) {
				indexFile(file, false, -1);
			} else {
				for (int i = 0; i < dequeues.length; i++) {
					file = dequeues[i].pollLast();
					if (file != null) {
						indexFile(file, i != index, i);
						continue outer;
					}
				}
			}
			if (dequeues[index].isEmpty()
					&& Thread.currentThread().isInterrupted()) {
				break;
			}
		}
		System.out
				.printf("Indexer-%d finished working (indexed %d files, including %d stolen ones, percent stolen = %d).\n",
						index, indexedCount, stolenCount, (stolenCount * 100)
								/ indexedCount);
	}

	public void indexFile(File file, boolean stolen, int stolenFrom) {
		long total = 0;
		try (FileInputStream fis = new FileInputStream(file);
				BufferedInputStream bis = new BufferedInputStream(fis)) {
			int available;
			while ((available = bis.available()) > 0) {
				byte[] b = new byte[available];
				total += bis.read(b);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("Total read: " + total + " bytes.");

		System.out.println((stolen ? "[STOLEN FROM " + stolenFrom + "] " : "")
				+ index + ": " + file.getAbsolutePath());
		indexedCount++;
		if (stolen && stolenFrom != index) {
			stolenCount++;
		}
	};
}